from fastapi import FastAPI, Depends, HTTPException, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from . import models, schemas, crud, database
import os

# 创建数据库表
models.Base.metadata.create_all(bind=database.engine)

app = FastAPI(
    title="FastAPI MySQL CRUD",
    description="A complete CRUD application with FastAPI and MySQL",
    version="1.0.0"
)

# 设置模板目录
templates = Jinja2Templates(directory=os.path.join(os.path.dirname(__file__), "templates"))

# API路由
@app.get("/api/products/", response_model=list[schemas.Product])
def read_products(
    skip: int = 0,
    limit: int = 100,
    category: str = None,
    db: Session = Depends(database.get_db)
):
    return crud.get_products(db, skip=skip, limit=limit, category=category)

@app.get("/api/products/{product_id}", response_model=schemas.Product)
def read_product(product_id: int, db: Session = Depends(database.get_db)):
    db_product = crud.get_product(db, product_id=product_id)
    if db_product is None:
        raise HTTPException(status_code=404, detail="Product not found")
    return db_product

@app.post("/api/products/", response_model=schemas.Product, status_code=201)
def create_product(product: schemas.ProductCreate, db: Session = Depends(database.get_db)):
    return crud.create_product(db=db, product=product)

@app.put("/api/products/{product_id}", response_model=schemas.Product)
def update_product(
    product_id: int,
    product: schemas.ProductUpdate,
    db: Session = Depends(database.get_db)
):
    db_product = crud.update_product(db, product_id=product_id, product=product)
    if db_product is None:
        raise HTTPException(status_code=404, detail="Product not found")
    return db_product

@app.delete("/api/products/{product_id}", status_code=204)
def delete_product(product_id: int, db: Session = Depends(database.get_db)):
    success = crud.delete_product(db, product_id=product_id)
    if not success:
        raise HTTPException(status_code=404, detail="Product not found")
    return

@app.get("/api/categories/", response_model=list[str])
def read_categories(db: Session = Depends(database.get_db)):
    categories = crud.get_categories(db)
    # 将结果转换为字符串列表
    return [category[0] for category in categories]

# Web界面路由
@app.get("/root", response_class=HTMLResponse)
async def read_root(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})